﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.Practices.Unity;
using System.Runtime.Caching;

namespace Biblioteca.Filters
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
    public class CacheResultAttribute : HandlerAttribute
    {

        public CacheResultAttribute()
        {
            CachingTime = TimeSpan.FromMinutes(1);
        }


        public CacheResultAttribute(int cacheTimeSeconds)
        {
            CachingTime = TimeSpan.FromSeconds(cacheTimeSeconds);
        }

        public TimeSpan CachingTime { get; set; }

        public override ICallHandler CreateHandler(IUnityContainer container)
        {
            return new CacheAttributeHandler(CachingTime);
        }
    }
     class CacheAttributeHandler : ICallHandler
    {

        public CacheAttributeHandler(TimeSpan cachingTime)
        {
            CachingTime = cachingTime;
            MemoryCache = MemoryCache.Default;
        }

        private MemoryCache MemoryCache { get; set; }
        private TimeSpan CachingTime { get; set; }



        public int Order { get; set; }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (MemoryCache.Contains(input.MethodBase.Name))
                return input.CreateMethodReturn(MemoryCache.Get(input.MethodBase.Name));

            IMethodReturn methodReturn = getNext()(input, getNext);

            MemoryCache.Add(input.MethodBase.Name, methodReturn.ReturnValue,
                               new CacheItemPolicy { SlidingExpiration = CachingTime });
            return methodReturn;
        }


    }
}